<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../../css/mui.css" rel="stylesheet" />
		<link href="../../css/header.css" rel="stylesheet" />
		<style>
			html,
			body {
				height: 100%;
			}
			
			.mui-content {
				height: 100%;
				overflow: auto;
			}
			
			.red-point{
		      position: relative;
		    }
			
		    .red-point::before{
		      content: " ";
		      border: 5px solid #C9394A;/*设置红色*/
		      border-radius:5px;/*设置圆角*/
		      position: absolute;
		      z-index: 3000;
		      right: 0%;
		      margin-right: -10px;
		      margin-top: 0px;
		    }
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav title">
			<span class="mui-action-back nav mui-pull-left title-color" style="line-height: 44px; margin-left: 5px;">雨信</span>
		</header>
		<div class="mui-content">
			<ul class="mui-table-view" id="ul_friend_request_list" style="margin-bottom: 10px;">

			</ul>
			<ul id="ul_chatSnapshot" class="mui-table-view">
			</ul>
		</div>
		<script src="../../js/mui.js"></script>
		<script src="../../js/app.js"></script>
		<script type="text/javascript">
			mui.init();

			mui.plusReady(function() {
				// 获取登录用户
				var user = app.getUserGlobalInfo();
				// 获取当前页面
				var currentWebview = plus.webview.currentWebview();
				var chat = currentWebview.chat;
				currentWebview.addEventListener("show", function() {
					// 加载好友请求记录
					loadingFriendRequests();
					// 加载聊天快照
					console.log("加载聊天快照")
					loadingChatSnapshot();
				});
				// 添加自定义事件，刷新好友请求，初始化websocket
				window.addEventListener("refresh", function() {
					console.log("refresh -> refresh")
					loadingFriendRequests(); // 加载好友请求记录
				});
				// 为聊天快照列表量绑定点击事件
				mui("#ul_chatSnapshot").on("tap", ".chat-with-friend", function(e) {
					var friendUserId = this.getAttribute("friendUserId");
					var friendNickname = this.getAttribute("friendNickname");
					var friendThumHeadPortrait = this.getAttribute("friendThumHeadPortrait");

					// 打开聊天子页面
					mui.openWindow({
						url: "chatting.html",
						id: "chatting-" + friendUserId, // 每个朋友的聊天页面都是唯一对应的
						extras: {
							chat: chat,
							friendUserId: friendUserId,
							friendNickname: friendNickname,
							friendThumHeadPortrait: friendThumHeadPortrait,
						}
					});

					// 标记未读状态为已读
					app.setChatSnapshotReaded(user.id, friendUserId);
					// 渲染快照列表进行展示
					loadingChatSnapshot();
				});


				// 左滑删除聊天快照和记录
				mui("#ul_chatSnapshot").on("tap", ".btn-delete", function(e) {
					var btnArray = ['取消', '删除'];
					mui.confirm('删除后，将清空该聊天的消息记录', ' ', btnArray, function(e) {
						if (e.index == 1) {
							var _this = this; // a 标签
							// 获取朋友id
							var friendUserId = _this.getAttribute("friendUserId");
							// 1. 删除本地聊天记录
							app.deleteChatHistory(user.id, friendUserId);
							// 2. 删除本地聊天快照
							app.deleteChatSnapshot(user.id, friendUserId);
							// 3. 移除当前用户操作的dom节点
							var li = _this.parentNode.parentNode; // 获取li标签
							var ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
							ul_chatSnapshot.removeChild(li); // 删除li标签
						}
					}, "div");
				});

			});


			// 加载好友请求记录列表
			function loadingFriendRequests() {
				// 获取用户全局对象
				var user = app.getUserGlobalInfo();
				mui.ajax(app.serverUrl + "/friend/request", {
					data: {
						userId: user.id,
						status: 0
					},
					dataType: 'json', //服务器返回json格式数据
					type: 'get', //HTTP请求类型
					timeout: 10000, //超时时间设置为10秒；
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						//服务器返回响应
						if (res.code == 0) {
							var friendRequestList = res.data;
							var ul_friend_request_list = document.getElementById("ul_friend_request_list");
							if (friendRequestList != null && friendRequestList.length > 0) {
								var requestHtml = "";
								for (var i = 0; i < friendRequestList.length; i++) {
									requestHtml += createFriendRequestsHtml(friendRequestList[i]);
								}
								ul_friend_request_list.innerHTML = requestHtml;
								bindBtnEvent();
							} else {
								ul_friend_request_list.innerHTML = "";
							}
						}
					},
					error: function(xhr, type, errorThrown) {
						//异常处理；
						app.showToast(type, "error");
					}
				});
			}

			// 绑定按钮tap事件
			function bindBtnEvent() {
				// 绑定忽略事件
				mui(".btnOper").on("tap", ".ignoreRequest", function(e) {
					var friendRequestId = this.getAttribute("friendRequestId");
					operatorFriendRequest(friendRequestId, -1);
				});
				// 绑定同意事件
				mui(".btnOper").on("tap", ".passRequest", function(e) {
					var friendRequestId = this.getAttribute("friendRequestId");
					operatorFriendRequest(friendRequestId, 1);
				});
			}

			// 忽略/同意好友请求
			function operatorFriendRequest(friendRequestId, status) {
				var user = app.getUserGlobalInfo();
				var params = {
					userId: user.id,
					friendRequestId: friendRequestId,
					status: status
				}
				console.log(JSON.stringify(params));
				mui.ajax(app.serverUrl + "/friend/operate", {
					data: params,
					dataType: 'json', //服务器返回json格式数据
					type: 'post', //HTTP请求类型
					timeout: 10000, //超时时间设置为10秒；
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						if (res.code == 0) {
							app.showToast(res.msg, "success");
							// 更新通讯录
							var myFriendList = res.data;
							app.setContactList(myFriendList);
							// 重新加载好友请求记录
							loadingFriendRequests();
						} else {
							app.showToast(res.msg, "error");
						}
					},
					error: function(xhr, type, errorThrown) {
						//异常处理；
						app.showToast(type, "error");
					}
				});
			}

			// 创建好友请求html
			function createFriendRequestsHtml(friendRequest) {
				var html = "";
				var imgUrl = '../../image/face-default-cat.png';
				if (friendRequest.sendUser.thumHeadPortrait) {
					imgUrl = friendRequest.sendUser.thumHeadPortrait;
				}
				html = '<li class="btnOper mui-table-view-cell mui-media">' +
					'<a href="javascript:;">' +
					'<img class="mui-media-object mui-pull-left" src="' + imgUrl + '">' +
					'<span id="span_nickname" class="mui-pull-right">' +
					'<button friendRequestId="' + friendRequest.id +
					'" type="button" class="ignoreRequest mui-btn mui-btn-grey" style="padding: 4px 10px;margin-right:5px;">忽略</button>' +
					'<button friendRequestId="' + friendRequest.id +
					'" type="button" class="passRequest mui-btn mui-btn-danger" style="padding: 4px 10px;">通过</button>' +
					'</span>' +
					'<div class="mui-media-body">' +
					'<label>' + friendRequest.sendUser.nickname + '</label>' +
					'<p class="mui-ellipsis">请求添加你为朋友</p>' +
					'</div>' +
					'</a>' +
					'</li>';
				return html;
			}

			// 展示聊天快照，渲染列表
			function loadingChatSnapshot() {
				var user = app.getUserGlobalInfo();
				var chatSnapshotList = app.getChatSnapshot(user.id);
				console.log(JSON.stringify(chatSnapshotList));
				var ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
				var chatItemHtml = "";
				ul_chatSnapshot.innerHTML = "";
				for (var i = 0; i < chatSnapshotList.length; i++) {
					var chatSnapshot = chatSnapshotList[i];
					var friendUserId = chatSnapshot.otherId;
					// 根据friendId从本地联系人列表的缓存中拿到相关信息
					var friend = app.getFriend(friendUserId);
					if (!friend) {
						console.log("未在缓存中查到相应的friend");
						return;
					}
					var imgUrl = '../../image/face-default-cat.png';
					if (chatSnapshot.type == 1) { // 自己发送的
						imgUrl = user.friendThumHeadPortrait ? user.friendThumHeadPortrait : imgUrl;
					} else { // 好友发送的
						imgUrl = chatSnapshot.friendThumHeadPortrait ? chatSnapshot.friendThumHeadPortrait : imgUrl;
					}
					var friendNickname = friend.friendNickname;
					// 判断消息的已读或未读状态
					var message = chatSnapshot.message;
					if (!message) {
						return;
					}
					var isRead = chatSnapshot.isRead;
					var readHtmlBefore = '';
					var readHtmlAfter = '';
					if (!isRead) {
						readHtmlBefore = '<span class="red-point">';
						readHtmlAfter = '</span>';
					}

					chatItemHtml = '<li friendUserId="' + friendUserId + '" friendNickname="' + friend.friendNickname +
						'" friendThumHeadPortrait="' + imgUrl + '" class="chat-with-friend mui-table-view-cell mui-media">' +
						'<div class="mui-slider-right mui-disabled">' +
						'<a friendUserId="' + friendUserId + '" class="mui-btn mui-btn-red btn-delete">删除</a>' +
						'</div>' +
						'<div class="mui-slider-handle mui-media-body ">' +
						'<img class="mui-media-object mui-pull-left" src="' + imgUrl + '"/>' +
						readHtmlBefore + friend.friendNickname + readHtmlAfter +
						'<p class="mui-ellipsis">' + message + '</p>' +
						'</div>' +
						'</li>';
					ul_chatSnapshot.insertAdjacentHTML('beforeend', chatItemHtml);
				}

			}
		</script>
	</body>

</html>
